#include "alertrecord.h"
#include "ui_alertrecord.h"
#include <QSqlQuery>
#include <QMessageBox>

AlertRecord::AlertRecord(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AlertRecord)
{
    ui->setupUi(this);
    QFile mainFile(":/qss/AlertManager.qss");
    if (mainFile.open(QFile::ReadOnly)) {
        QString styleSheet = QLatin1String(mainFile.readAll());
        this->setStyleSheet(styleSheet);
        qDebug() <<"AlertManager QSS打开成功";
    }else{
        qDebug() <<"AlertManager QSS打开失败";
    }
    ui->deviceLineEdit->setPlaceholderText("请输入设备名称");
    ui->contentEdit->setPlaceholderText("请输入告警内容");
    setupModel();
    setupConnections();
    //设置定时器，每隔31秒刷新一次告警记录
    refreshRecordTimer=new QTimer(this);
    connect(refreshRecordTimer,&QTimer::timeout,this,&AlertRecord::onRefreshRecord);
    refreshRecordTimer->start(31000);

}

AlertRecord::~AlertRecord()
{
    delete ui;
}

void AlertRecord::onSelectRecords()
{
    QString filter;

    // 获取设备ID
    QString deviceName = ui->deviceLineEdit->text();
    if (!deviceName.isEmpty()) {
        SQLiteDatabase* db = SQLiteDatabase::getInstance();
        QSqlQuery query(db->getConnection());
        query.prepare("SELECT device_id FROM devices WHERE name = ?");
        query.addBindValue(deviceName);
        if (query.exec() && query.next()) {
            int deviceId = query.value(0).toInt();
            filter += QString("device_id = %1").arg(deviceId);
            qDebug()<<deviceId;
        } else {
            QMessageBox::warning(this, "Search Error", "Device not found");
            return;
        }
    }
    //获取时间范围
    QDate startDate = ui->startDateEdit->date();
    QDate endDate = ui->endDateEdit->date();
    if (startDate.isValid() && endDate.isValid()) {
        if (!filter.isEmpty()) filter += " AND ";
        filter += QString("timestamp BETWEEN '%1' AND '%2'")
                      .arg(startDate.toString("yyyy-MM-dd"))
                      .arg(endDate.toString("yyyy-MM-dd"));
    }
    // 获取告警内容
    QString content = ui->contentEdit->text();
    if (!content.isEmpty()) {
        if (!filter.isEmpty()) filter += " AND ";
        filter += QString("content LIKE '%%1%'").arg(content);
    }

    model->setFilter(filter);
    model->select();
}

void AlertRecord::onResetSelect()
{
    ui->deviceLineEdit->clear();
    ui->startDateEdit->setDate(QDate::currentDate().addMonths(-1));
    ui->endDateEdit->setDate(QDate::currentDate());
    ui->contentEdit->clear();
    model->setFilter("");
    model->select();
}

void AlertRecord::onRefreshRecord()
{
    model->select();
}

void AlertRecord::setupModel()
{
    SQLiteDatabase* db=SQLiteDatabase::getInstance();
    model=new QSqlTableModel(this,db->getConnection());
    model->setTable("alarm_records");
    model->select();
    // 设置自定义列标题
    model->setHeaderData(0, Qt::Horizontal, tr("记录ID"));
    model->setHeaderData(1, Qt::Horizontal, tr("设备ID"));
    model->setHeaderData(2, Qt::Horizontal, tr("时间戳"));
    model->setHeaderData(3, Qt::Horizontal, tr("告警内容"));
    model->setHeaderData(4, Qt::Horizontal, tr("处理状态"));
    model->setHeaderData(5, Qt::Horizontal, tr("处理备注"));

    ui->showRecordTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //自适应
    ui->showRecordTableView->setModel(model);
}

void AlertRecord::setupConnections()
{
    connect(ui->selectBtn,&QAbstractButton::clicked,this,&AlertRecord::onSelectRecords);
    connect(ui->resetBtn,&QAbstractButton::clicked,this,&AlertRecord::onResetSelect);
}
